package multithreading;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

public class AddPrintingCount {
    public static void main(String[] args) {
        Counter counter = new Counter();
        Thread[] threads = new Thread[5];
        for(int i = 0; i < 5; i++) {
            threads[i] = new Thread(new CounterThread(counter));
            threads[i].start();
        }
        for(Thread thread: threads) {
            try {
            thread.join();
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }

       int count = counter.getCount();
       System.out.println(count);
    }
}

class Counter {
    private volatile int count = 0;
    // 创建一个初始值为0的AtomicInteger对象
    AtomicInteger atomicInteger = new AtomicInteger(0);
    Object lock = new Object();
    public synchronized void increment(int count1) {
        // 写的时候把读锁给拿了
        atomicInteger.incrementAndGet();
        if (check(count1)) {
            // 不同线程来加值，跑得快的先加
            count++;
            System.out.println(Thread.currentThread().getName() + " " + count);
        }
        atomicInteger.decrementAndGet();
    }

    public synchronized int getCount() {
        while (atomicInteger.get() != 0) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return count;
    }
    
    public boolean check(int count) {
       return this.count == count;
    }
}

class CounterThread implements Runnable{
    private int count = 0;
    private Counter counter = null;

    CounterThread(Counter counter) {
        this.counter = counter;
    }

    public void increment() {
        count++;
    }

    public int getCount() {
        return count;
    }

    @Override
    public void run() {
        int var = 0;
        while (var < 10000) {
            counter.increment(var);
            // 相加之后就开始获取值，紧接着就要开始判断。
            var = counter.getCount();
        }
    }
}